package com.kafka.study.consumer;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ProcessConsumer {
    @Resource(name = "deadKafkaTemplate")
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${spring.kafka.template.dead-topic}")
    private String deadTopic;

    @KafkaListener(topics = "${spring.kafka.template.business-topic}",
            containerFactory = "businessKafkaListenerContainer")
    public void businessListener(ConsumerRecord<String, String> record) {
        try {
            log.info("received message, [{}]", record.value());
        } catch (Exception ex) {
            log.error("something wrong", ex);
            ProducerRecord<String, String> aRecord
                    = new ProducerRecord<>(deadTopic, null, record.timestamp(), record.key(), record.value(), record.headers());
            kafkaTemplate.send(aRecord);
        }
    }
}
